package top.archiesean.common.security.component;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import top.archiesean.common.core.domain.R;
import top.archiesean.common.core.enums.RespStatus;
import top.archiesean.common.core.utils.resp.ResponseUtils;


/**
 * @author ArchieSean
 * @description 资源服务器认证异常处理端点
 * @date 2024-01-23 16:35
 */
@Slf4j
public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) {
        R<Object> result = null;

        if (authException != null) {
            log.error("资源服务器认证异常：{}", authException.getMessage());
            result = R.fail(RespStatus.UNAUTHORIZED.getCode(), authException.getMessage());
        }
        //针对令牌过期，状态码设置为 402
        if (authException instanceof InvalidBearerTokenException
                || authException instanceof InsufficientAuthenticationException) {
            log.error("令牌已过期，{}", authException.getMessage());
            result = R.fail(RespStatus.TOKEN_TIME_OUT);
        }

        //响应
        ResponseUtils.out(response, result);
    }
}
